<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>图书添加案例</title>
    <style type="text/css">
      .grid {
        margin: auto;
        width: 530px;
        text-align: center;
      }
      .grid table {
        border-top: 1px solid #c2d89a;
        width: 100%;
        border-collapse: collapse;
      }
      .grid th,
      td {
        padding: 10;
        border: 1px dashed #f3dcab;
        height: 35px;
        line-height: 35px;
      }
      .grid th {
        background-color: #f3dcab;
      }
      .grid .book {
        padding-bottom: 10px;
        padding-top: 5px;
        background-color: #f3dcab;
      }
      .grid .total {
        height: 30px;
        line-height: 30px;
        background-color: #f3dcab;
        border-top: 1px solid #c2d89a;
      }
    </style>
  </head>
  <body>
    <div id="app">
      <div class="grid">
        <div>
          <h1>图书管理</h1>
          <div class="book">
            <div>
              <label for="id">
                编号：
              </label>
              <input type="text" v-model.number="addid" :disabled="disable" />
              <label for="name">
                名称：
              </label>
              <input type="text" id="name" v-model.trim="addname" />
              <button @click="submit" :disabled="submitDisable">
                提交
              </button>
            </div>
          </div>
        </div>
        <div class="total">
          <span>图书总数：</span>
          <span></span>
        </div>
        <table>
          <thead>
            <tr>
              <th>编号</th>
              <th>名称</th>
              <th>时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-bind:key="item.id" v-for="item in books">
              <td>{{item.id}}</td>
              <td>{{item.name}}</td>
              <td>{{item.date | form('yyyy-MM-dd')}}</td>
              <td>
                <a href="" @click.prevent="edit(item.id)">修改</a>
                <span>|</span>
                <a href="" @click.prevent="del(item.id)">删除</a>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <script src="../node_modules/vue/dist/vue.js"></script>
    <script>
      //时间过滤器
      Vue.filter('form', function (data, params) {
        /**
         * 对日期进行格式化，
         * @param date 要格式化的日期
         * @param format 进行格式化的模式字符串
         *     支持的模式字母有：
         *     y:年,
         *     M:年中的月份(1-12),
         *     d:月份中的天(1-31),
         *     h:小时(0-23),
         *     m:分(0-59),
         *     s:秒(0-59),
         *     S:毫秒(0-999),
         *     q:季度(1-4)
         * @return String
         * @author yanis.wang
         * @see http://yaniswang.com/frontend/2013/02/16/dateformat-performance/
         */
        function dateFormat(date, format) {
          if (typeof date === 'string') {
            var mts = date.match(/(\/Date\((\d+)\)\/)/)
            if (mts && mts.length >= 3) {
              date = parseInt(mts[2])
            }
          }
          date = new Date(date)
          if (!date || date.toUTCString() == 'Invalid Date') {
            return ''
          }
          var map = {
            M: date.getMonth() + 1, //月份
            d: date.getDate(), //日
            h: date.getHours(), //小时
            m: date.getMinutes(), //分
            s: date.getSeconds(), //秒
            q: Math.floor((date.getMonth() + 3) / 3), //季度
            S: date.getMilliseconds(), //毫秒
          }

          format = format.replace(/([yMdhmsqS])+/g, function (all, t) {
            var v = map[t]
            if (v !== undefined) {
              if (all.length > 1) {
                v = '0' + v
                v = v.substr(v.length - 2)
              }
              return v
            } else if (t === 'y') {
              return (date.getFullYear() + '').substr(4 - all.length)
            }
            return all
          })
          return format
        }
        // DateFormat(data, params)
        return dateFormat(data, params)
      })
      new Vue({
        el: '#app',
        data: {
          submitDisable: false,
          disable: false, //禁用编号
          addid: '',
          addname: '',
          books: [
            { id: 1, name: '语文', date: '2018-10-3' },
            { id: 2, name: '数学', date: '2018-03-3' },
            { id: 3, name: '英语', date: '2014-10-3' },
            { id: 4, name: '物理', date: '2015-10-3' },
          ],
        },
        methods: {
          //提交数据
          submit() {
            if (this.addid.toString().length > 0 && this.addname.length > 0) {
              //判断是否为编辑状态
              if (this.disable) {
                this.books.some((item) => {
                  if (item.id == this.addid) {
                    item.name = this.addname
                  }
                  return true
                })
                this.addid = this.addname = ''
                //把禁用编号标签归为
                this.disable = false
                return
              }

              //如果id为数字时进行添加
              if (!isNaN(this.addid)) {
                let addbook = {
                  id: this.addid,
                  name: this.addname,
                  date: new Date(),
                }
                this.books.push(addbook)
                this.addid = this.addname = ''
              } else {
                alert('请在标签输入数字')
              }
            } else {
              alert('请填写标签或书名')
            }
          },
          //   单击修改时把id和name放到提交按钮那一组,some返回的是boolean
          edit(id) {
            // 单击编辑时把编号禁用
            this.disable = true
            var findbook = this.books.filter((item) => {
              return item.id === id
            })
            //数据显示
            this.addid = findbook[0].id
            this.addname = findbook[0].name
          },
          del(id) {
            const index = this.books.findIndex((item) => {
              return item.id === id
            })
            this.books.splice(index, 1)
          },
        },
        watch: {
          //数据优化，单击内容没有改变时与服务端不会进行交互
          addname() {
            //   查找修改项或者添加项，不能重复名
            var value = this.books.filter((item) => {
              return item.id == this.addid
            })

            // 把提交按钮禁用
            if (value[0].name === this.addname) {
              this.submitDisable = true
            } else {
              this.submitDisable = false
            }
          },
        },
        computed: {},
      })
    </script>
  </body>
</html>
